<template>
  <el-dialog
    title="提示"
    :visible="dialogVisible"
    width="30%"
    @close="closedialog"
  >
    <template #default>
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
    </template>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closedialog">取 消</el-button>
      <el-button type="primary" @click="login">确 定</el-button>
    </span>
  </el-dialog>

</template>

<script>
import { addRoleAPI, getRoleDetail, updateRole } from '@/api/settings'
export default {
  name: '',

  components: {

  },

  filters: {},
  props: {
    dialogVisible: {
      type: Boolean
    }
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称必填', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述必填', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  mounted() {
    // this.geteditRole()
  },
  methods: {
    // 关闭弹框
    closedialog() {
      console.log(111)
      this.$emit('close-dialog')
    },
    // 兜底校验
    login() {
      // 调用validate
      this.$refs.roleForm.validate(async vaild => {
        if (!vaild) return

        if (this.roleForm.id) {
          await updateRole(this.roleForm)
        } else {
          // 调用新增姐寇
          await addRoleAPI(this.roleForm)
        }
        // 成功弹框
        this.$message.success(`${this.roleForm.id ? '编辑' : '新增'}成功`)
        // 通过子传父 重新渲染数据
        this.$emit('getRole')
        // 后续逻辑
        this.resetFrom()
      })
    },
    resetFrom() {
      // 通过子传父 调用关闭弹框方法
      this.$emit('close-dialog')
      // 调用eleui的重置表单
      this.$refs.roleForm.resetFields()
      // 清空数据
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 获取数据回填数据
    async  geteditRole(id) {
      // console.log(id)
      const res = await getRoleDetail(id)
      this.roleForm = res
    }
  }
}
</script>

<style lang="less" scoped>

</style>
